
package com.mengmeizi.db;

import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

import java.io.File;

public class DBHelper extends SQLiteOpenHelper {

    private static int DBVersion = 2;

    private static String DBName = "pictures.db";

    private SQLiteDatabase sqlDb;

    private String tableName;

    /** 用于对空值的替代。 */
    public static final String DB_NULL_COLUMN = "NULL_COLUMN";

    public DBHelper(Context context, String tabelName) {
        super(context, DBName, null, DBVersion);
        this.tableName = tabelName;
        File dbFile = context.getDatabasePath(DBName);
        if (!dbFile.exists()) {
            openWritableDatabase();
            close();
        }
    }

    @Override
    public void onCreate(SQLiteDatabase db) {
        // TODO Auto-generated method stub
        String sql = WallpaperDBBean.sql$createTable();
        Log.v(DBName, "sql[" + sql + "]");
        db.execSQL(sql);
        sql = ImageBufferDB.sql$createTable();
        Log.v(DBName, "sql[" + sql + "]");
        db.execSQL(sql);
    }

    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 删除旧表
        db.execSQL(WallpaperDBBean.sql$dropTabel());
        db.execSQL(ImageBufferDB.sql$dropTable());
        // 创建新表
        db.execSQL(WallpaperDBBean.sql$createTable());
        db.execSQL(ImageBufferDB.sql$createTable());
    }

    public Cursor getDatas(String sql) {
        return sqlDb.rawQuery(sql, null);
    }

    /** 插入一条记录 */
    public long insertItem(ContentValues values) {
        return sqlDb.insert(tableName, DB_NULL_COLUMN, values);
    }

    /** 删除一条记录 */
    public int deleteItem(String sql) {
        return sqlDb.delete(tableName, sql, null);
    }

    /** 清除表中所有的数据内容。 */
    public void clearAllRecord() {
        String sql = "delete from '" + tableName + "'";
        sqlDb.execSQL(sql);
    }

    /** 删除表操作。 */
    public void dropTable() {
        String sql = "drop table '" + tableName + "'";
        sqlDb.execSQL(sql);
    }

    public void openWritableDatabase() {
        this.close();
        sqlDb = this.getWritableDatabase();
    }

    public void openReadableDatabase() {
        this.close();
        sqlDb = this.getReadableDatabase();
    }

    @Override
    public void close() {
        if (sqlDb != null) {
            sqlDb.close();
        }
        super.close();
    }
}
